//
//  BVEditVideoViewController.m
//  BVHomeScene
//
//  Created by xiute on 2019/10/24.
//

#import "BVEditVideoViewController.h"
#import "Masonry.h"
#import <SVProgressHUD.h>
#import "GPUImage.h"z

@interface BVEditVideoViewController ()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navTopMargin;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIView *videoView;
@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;
@property (weak, nonatomic) IBOutlet UIButton *button3;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *videoViewHeight;

@property (nonatomic, strong) GPUImageMovie *movie;
@property (nonatomic, strong) GPUImageMovieWriter *writer;

@property (nonatomic, strong) GPUImageView *movieView;

@property (nonatomic, strong) GPUImageFilter *filter;


@property (nonatomic, assign) NSInteger selectTag;

@property (nonatomic, assign) BOOL onceLock;

@end

@implementation BVEditVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectTag = -1;
    [self loadInitData];
    
}

- (void)loadInitData {
    self.filter = [[GPUImageFilter alloc] init];
    [self.movie addTarget:self.filter];
    [self.filter addTarget:self.movieView];
    
    [self.videoView addSubview:self.movieView];
    [self.movieView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.videoView);
    }];
    [self.movie startProcessing];
    AVURLAsset *asset = [AVURLAsset assetWithURL:self.videoUrl];
    self.videoViewHeight.constant = kSCREEN_WIDTH * (asset.naturalSize.height / asset.naturalSize.width);
    
}


- (void)setupViews {
    self.navTopMargin.constant = isIPhoneX ? 44 : 20;
    self.backButton.contentEdgeInsets = UIEdgeInsetsMake(11, 11, 11, 11);
}

- (IBAction)backButtonAct:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)saveVideoAct:(id)sender {
    [self.movie endProcessing];
    [self.filter removeTarget:self.movieView];
    [self.movie removeTarget:self.filter];
    [self.movieView removeFromSuperview];
    self.filter = nil;
    self.movie = nil;
    
    
    
    NSURL *sampleURL = self.videoUrl;
    
    // 初始化 movie
    _movie = [[GPUImageMovie alloc] initWithURL:sampleURL];
    _movie.shouldRepeat = NO;
    _movie.playAtActualSpeed = YES;
    
    // 设置加滤镜视频保存路径
    NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.mp4"];
    unlink([pathToMovie UTF8String]);
    NSURL *movieURL       = [NSURL fileURLWithPath:pathToMovie];
    
    // 初始化
    _writer = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(self.videoView.width * 2, self.videoView.height * 2)];
    _writer.encodingLiveVideo = NO;
    _writer.shouldPassthroughAudio = NO;
    
    /**
     如果你设置了 _movie.audioEncodingTarget = _writer;
     会报如下错误：
     *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVAssetWriterInput appendSampleBuffer:] Cannot append sample buffer: Input buffer must be in an uncompressed format when outputSettings is not nil'
     暂时没去深究，以后再解决！
     */
    
    // 添加滤镜
    GPUImageFilter *filter;
    switch (self.selectTag) {
        case 0: {
            filter = [[GPUImageToonFilter alloc] init];
        }
            break;
        case 1: {
            filter = [[GPUImageThresholdSketchFilter alloc] init];
        }
            break;
        case 2: {
            filter = [[GPUImageThresholdEdgeDetectionFilter alloc] init];
        }
            break;
        default:
            filter = [[GPUImageFilter alloc] init];
            break;
    }
    [_movie addTarget:filter];
    [filter addTarget:_writer];
    
    [_movie enableSynchronizedEncodingUsingMovieWriter:_writer];
    [_writer startRecording];
    [_movie startProcessing];
    
    __weak typeof(self) weakSelf = self;
    [SVProgressHUD showWithStatus:@"保存中..."];
    [_writer setCompletionBlock:^{
        NSLog(@"OK");
        [SVProgressHUD dismiss];
        UISaveVideoAtPathToSavedPhotosAlbum(pathToMovie, weakSelf, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        [filter removeTarget:weakSelf.writer];
        [weakSelf.writer finishRecording];
    }];
    
    
}



- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败 请重试"];
    }
    else {
        [SVProgressHUD showSuccessWithStatus:@"保存视频成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }
  
}

- (IBAction)changeVideoFilterAct:(UIButton *)sender {
    BOOL senderSelect = sender.selected;
    self.button1.backgroundColor = [UIColor colorFromHexString:@"e0623e"];
    self.button2.backgroundColor = [UIColor colorFromHexString:@"e0623e"];
    self.button3.backgroundColor = [UIColor colorFromHexString:@"e0623e"];
    
    [self.button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.button2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.button3 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    self.button1.selected = NO;
    self.button2.selected = NO;
    self.button3.selected = NO;
    
    [self.movie removeTarget:self.filter];
    if (!senderSelect) {
        sender.selected = YES;
        [sender setTitleColor:[UIColor colorFromHexString:@"333333"] forState:UIControlStateNormal];
        sender.backgroundColor = [UIColor yellowColor];
        switch (sender.tag) {
            case 0: {
                self.filter = [[GPUImageToonFilter alloc] init];
            }
                break;
            case 1: {
                self.filter = [[GPUImageThresholdSketchFilter alloc] init];
            }
                break;
            case 2: {
                self.filter = [[GPUImageThresholdEdgeDetectionFilter alloc] init];
            }
                break;
            default:
                break;
        }
        self.selectTag = sender.tag;
    }else {
        self.filter = [[GPUImageFilter alloc]init];
    }
    
    [self.movie addTarget:self.filter];
    if (self.movieView != nil) {
        [self.movieView removeFromSuperview];
    }
    
    [self.filter addTarget:self.movieView];
    [self.videoView addSubview:self.movieView];
    [self.movieView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.videoView);
    }];
}

- (GPUImageMovie *)movie {
    if (!_movie) {
        self.movie = [[GPUImageMovie alloc] initWithURL:self.videoUrl];
        _movie.shouldRepeat = YES;
        _movie.playAtActualSpeed = YES;
    }
    return _movie;
}

- (GPUImageView *)movieView {
    if (!_movieView) {
        _movieView = [[GPUImageView alloc] init];
        _movieView.backgroundColor = [UIColor blackColor];
    }
    return _movieView;
}


@end
